#include "image.h"

XImage* load_png_image(Display *dpy, int screen, char *image_path, int *width, int *height) {
    FILE *fp = fopen(image_path, "rb");
    if (!fp) {
        return NULL;
    }
    png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
    png_infop info_ptr = png_create_info_struct(png_ptr);
    png_init_io(png_ptr, fp);
    png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_EXPAND, NULL);
    *width = png_get_image_width(png_ptr, info_ptr);
    *height = png_get_image_height(png_ptr, info_ptr);
    char *image_str = (char*)malloc(sizeof(int) * ((*width) * (*height)));
    png_bytep *row_pointers = png_get_rows(png_ptr, info_ptr);
    XImage *ximage = XCreateImage(dpy, DefaultVisual(dpy, 0), DefaultDepth(dpy, screen), ZPixmap, 0, image_str, *width, *height, 32, 0);
    for(int y = 0; y < *height; y++) {
        png_bytep row = row_pointers[y];
        for(int x = 0; x < *width; x++) {
            png_bytep px = &(row[x * 4]);
            XPutPixel(ximage, x, y, (px[0] << 16) | (px[1] << 8) | px[2]);
        }
    }
    free(image_str);
    return ximage;
}
